<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "admin_group".
 *
 * @property string $id
 * @property string $name
 * @property string $acl
 * @property integer $status
 * @property integer $created_at
 * @property string $created_by
 * @property integer $updated_at
 * @property string $updated_by
 */
class AdminGroup extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'admin_group';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['name'], 'unique'],
            [['acl'], 'string'],
            [['status', 'created_at', 'created_by', 'updated_at', 'updated_by'], 'integer'],
            [['name'], 'string', 'max' => 50],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '权限名',
            'acl' => '分组权限',
            'status' => '分组状态，0：不可用，1：可用',
            'created_at' => '创建时间',
            'created_by' => '添加人',
            'updated_at' => '更新时间',
            'updated_by' => '更新人',
        ];
    }

    /**
     * @inheritdoc
     * @return \app\models\query\AdminGroupQuery the active query used by this AR class.
     */
    public static function find()
    {
        return new \app\models\query\AdminGroupQuery(get_called_class());
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->created_at = $this->updated_at = time();
            $this->created_by = $this->updated_by = Yii::$app->user->id;
        } else {
            $this->updated_at = time();
            $this->updated_by = Yii::$app->user->id;
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($insert) {
            AdminLog::log("新添权限：" . $this->name, "create");
        } else {
            AdminLog::log("更新权限：旧：" . $changedAttributes['name'] . "；新：" . $this->name);
        }
    }

    public function afterDelete()
    {
        parent::afterDelete();
        AdminLog::log("删除权限：" . $this->name, "delete");
    }
}
